package com.alm.token.ui.activity;

import android.Manifest;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.InviteFriendsData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.BaseView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.alm.token.utils.LanguageUtils;
import com.alm.token.utils.Utils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yzq.zxinglibrary.encode.CodeCreator;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
//import com.uuzuche.lib_zxing.activity.CodeUtils;

public class InviteFriendActivity extends BaseActivity implements BaseView<InviteFriendsData> {
    @BindView(R.id.tv_topmsg)
    TextView tvTopMsg;
    @BindView(R.id.tv_invidecode)
    TextView tvInvidecode;
    @BindView(R.id.tv_invidecodecopy)
    TextView tvInvidecodecopy;
    @BindView(R.id.img_adressqrcode)
    ImageView imgAdressqrcode;
    //    @BindView(R.id.tv_savebitmap)
    TextView tvSavebitmap;

    //    @BindView(R.id.tv_copy)
    TextView tvCopy;
    @BindView(R.id.ly_qrcodebody)
    LinearLayout lyQrcodeBody;
    @BindView(R.id.tv_click_saveimg)
    TextView tv_click_saveimg;
    @BindView(R.id.tv_click_shareadress)
    TextView tv_click_shareadress;
    //    private QRCodeEncode.Builder builder;
    private Bitmap qrCodeBitmap = null;
    private Bitmap bodyBitmap = null;
    private String xiazaiuri = "";

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_invite_friend;
    }

    @Override
    protected void initVariables() {
//        if (!TextUtils.isEmpty(ConStant.UPDATEAPPURI)) {
//            xiazaiuri = ConStant.UPDATEAPPURI;
//        }
    }

    @Override
    protected void initViews() {

        new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item5));//setRightIcon(R.drawable.association_white, this)

        if (LanguageUtils.getSetIndex() == 1) {
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_invitefriends));
        } else if (LanguageUtils.getSetIndex() == 3) {
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_invitefriends3));
        } else if (LanguageUtils.getSetIndex() == 4) {
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_invitefriends4));
        } else {
            lyQrcodeBody.setBackground(getResources().getDrawable(R.drawable.icon_invitefriends_en));
        }
    }

    @Override
    protected void loadData() {
//        if (MyApp.getUserData() != null && MyApp.getUserData().getData() != null && MyApp.getUserData().getData().getUser() != null) {
//            tvInvidecode.setText(MyApp.getUserData().getData().getUser().getCode());
//            initAddressQRCode();
//        }
        preenter.getInviteFriendsData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rightItem:
                startActivity(GroupActivity.class);
                break;
            case R.id.tv_click_saveimg:
            case R.id.ly_qrcodebody:
            case R.id.tv_savebitmap:
                if (bodyBitmap == null) {
                    showToast(getString(R.string.network_loading_hint1));
                    break;
                }
                //存储权限
                RxPermissions rxPermissions = new RxPermissions(this);
                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Observer<Boolean>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                            }

                            @Override
                            public void onNext(Boolean granted) {
                                if (granted) {
                                    tvInvidecodecopy.setVisibility(View.GONE);
                                    if (saveImageToGallery(InviteFriendActivity.this, bodyBitmap, CommonUtil.getStringDate() + getString(R.string.profile_hint_item17))) {
                                        showToast(getString(R.string.profile_hint_item15));
                                        if (EmptyUtils.isNotEmpty(tvSavebitmap)) {
                                            tvSavebitmap.setText(getString(R.string.profile_hint_item16));
                                        }
                                    }
                                    tvInvidecodecopy.setVisibility(View.VISIBLE);
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                            }

                            @Override
                            public void onComplete() {
                            }
                        });

                break;
            case R.id.tv_click_shareadress:
            case R.id.tv_copy:
                if (xiazaiuri.isEmpty()) {
                    showToast(getString(R.string.network_loading_hint1));
                    break;
                }
                copyWalletAddress(xiazaiuri);
                break;
        }

    }

    private void initAddressQRCode() {

//        layoutView(lyQrcodeBody,CommonUtil.px2dip(this,470),CommonUtil.px2dip(this,600));

        qrCodeBitmap = CodeCreator.createQRCode(xiazaiuri,
                CommonUtil.dip2px(this, 130),
                CommonUtil.dip2px(this, 130),
                BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        imgAdressqrcode.setImageBitmap(qrCodeBitmap);

        bodyBitmap = CommonUtil.getBitMapFromView(lyQrcodeBody);
    }


    private void layoutView(View v, int width, int height) {
        // validate view.width and view.height
        v.layout(0, 0, width, height);
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
        // validate view.measurewidth and view.measureheight
        v.measure(measuredWidth, measuredHeight);
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    }


    private void copyWalletAddress(String msg) {
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 将文本内容放到系统剪贴板里。
        if (cm != null) {
            // 创建普通字符型ClipData

            ClipData mClipData = ClipData.newPlainText("Label", msg);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
        }
        showToast(getString(R.string.profile_hint_item14));
        if (EmptyUtils.isNotEmpty(tvCopy)) {
            tvCopy.setText(getString(R.string.profile_hint_item14));
        }
    }

    /**
     * 保存图片到指定路径
     *
     * @param context
     * @param bitmap   要保存的图片
     * @param fileName 自定义图片名称
     * @return
     */
    public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
        //系统相册目录
        String storePath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;

        // 保存图片至指定路径
//        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode";


        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片(80代表压缩20%)
            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            fos.flush();
            fos.close();

            //发送广播通知系统图库刷新数据
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @OnClick({R.id.tv_invidecodecopy})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.tv_invidecodecopy:
                if (tvInvidecode.getText().toString().isEmpty()) {
                    showToast(getString(R.string.network_loading_hint1));
                    break;
                }
                copyWalletAddress(tvInvidecode.getText().toString());
                break;
        }
    }

    @Override
    public void getData(InviteFriendsData inviteFriendsData) {
        if (inviteFriendsData.getStatus() == 0) {
            //data : ["xfj001","15338834638","f2008","http://v.babih.com/app/pageApi/register?userid=2008"]
            List<String> datas = inviteFriendsData.getData();

            if (datas != null && datas.size() == 4) {
                if (!TextUtils.isEmpty(datas.get(0))) {
                    tvTopMsg.setText(getString(R.string.invite_hint_code1, datas.get(0).substring(0, 2) + "****" + datas.get(0).substring(datas.get(0).length() - 2, datas.get(0).length())));
                }
                if (!TextUtils.isEmpty(datas.get(2))) {
                    tvInvidecode.setText(datas.get(2));
                }
                if (!TextUtils.isEmpty(datas.get(3))) {
                    xiazaiuri = datas.get(3);
                    if (LanguageUtils.getSetIndex() == 1) {
                        xiazaiuri = datas.get(3) + "&lang=zh_CN";
                    } else if (LanguageUtils.getSetIndex() == 3) {
                        xiazaiuri = datas.get(3) + "&lang=ko_KR";
                    } else if (LanguageUtils.getSetIndex() == 4) {
                        xiazaiuri = datas.get(3) + "&lang=ja_JP";
                    } else {
                        xiazaiuri = datas.get(3) + "&lang=en_US";
                    }

                    initAddressQRCode();
//                    lyQrcodeBody.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
////                            showPopwindow();
//
//
//
//
//
//
//                        }
//                    });
                    tv_click_saveimg.setOnClickListener(this);
                    tv_click_shareadress.setOnClickListener(this);
//                    tv_click_saveimg.set
                }
            }

        } else {
            showToast(inviteFriendsData.getMsg());
        }


    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(this,PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            finish();
            showToSetPaypswDialog();
        }else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {

        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {

        hideWaitDialog();
    }


    PopupWindow popWindow;

    private void showPopwindow() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.activity_invite_select, null);

        tvSavebitmap = popView.findViewById(R.id.tv_savebitmap);
        tvCopy = popView.findViewById(R.id.tv_copy);

        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;

        if (popWindow == null) {
            popWindow = new PopupWindow(popView, width, Utils.dp2px(this, 130));
//            popWindow.setAnimationStyle(R.style.BottomToTopAnim);
            popWindow.setFocusable(true);
            popWindow.setOutsideTouchable(true);// 设置同意在外点击消失
            tvSavebitmap.setOnClickListener(this);
            tvCopy.setOnClickListener(this);
        }

        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
}


//package com.alm.token.ui.activity;
//
//        import android.Manifest;
//        import android.content.ClipData;
//        import android.content.ClipboardManager;
//        import android.content.Context;
//        import android.content.Intent;
//        import android.graphics.Bitmap;
//        import android.graphics.BitmapFactory;
//        import android.graphics.Canvas;
//        import android.graphics.drawable.ColorDrawable;
//        import android.net.Uri;
//        import android.os.Bundle;
//        import android.os.Environment;
//        import android.text.TextUtils;
//        import android.view.Gravity;
//        import android.view.View;
//        import android.view.ViewGroup;
//        import android.widget.ImageView;
//        import android.widget.LinearLayout;
//        import android.widget.PopupWindow;
//        import android.widget.TextView;
//
//        import com.alm.token.ConStant;
//        import com.alm.token.MyApp;
//        import com.alm.token.R;
//        import com.alm.token.base.BaseActivity;
//        import com.alm.token.ui.data.bean.InviteFriendsData;
//        import com.alm.token.ui.data.bean.MyTeamData;
//        import com.alm.token.ui.persenter.MyPreenter;
//        import com.alm.token.ui.view.BaseView;
//        import com.alm.token.ui.view.MineView;
//        import com.alm.token.utils.ActionBarHelper;
//        import com.alm.token.utils.CommonUtil;
//        import com.alm.token.utils.Utils;
//        import com.tbruyelle.rxpermissions2.RxPermissions;
//        import com.uuzuche.lib_zxing.activity.CodeUtils;
//
//        import java.io.File;
//        import java.io.FileOutputStream;
//        import java.io.IOException;
//        import java.util.List;
//        import java.util.zip.Inflater;
//
//        import butterknife.BindView;
//        import butterknife.ButterKnife;
//        import butterknife.OnClick;
//        import io.reactivex.Observer;
//        import io.reactivex.disposables.Disposable;
//
//public class InviteFriendActivity extends BaseActivity implements MineView<Object> {
//
//    @BindView(R.id.tv_invidecode)
//    TextView tvInvidecode;
//    @BindView(R.id.img_adressqrcode)
//    ImageView imgAdressqrcode;
//    @BindView(R.id.tv_savebitmap)
//    TextView tvSavebitmap;
//    @BindView(R.id.tv_copy)
//    TextView tvCopy;
//    @BindView(R.id.ly_qrcodebody)
//    LinearLayout lyQrcodeBody;
//    //    private QRCodeEncode.Builder builder;
//    private Bitmap qrCodeBitmap = null;
//    private Bitmap bodyBitmap = null;
//    private String xiazaiuri = "";
//
//    @Override
//    protected MyPreenter initPreenter() {
//        return new MyPreenter(this);
//    }
//
//    @Override
//    protected int getContentViewId() {
//        return R.layout.activity_invite_friend;
//    }
//
//    @Override
//    protected void initVariables() {
////        if (!TextUtils.isEmpty(MyApp.getUpdateApkUrl())) {
////            xiazaiuri = MyApp.getUpdateApkUrl();
////        }
//        if (!TextUtils.isEmpty(ConStant.UPDATEAPPURI)) {
//            xiazaiuri = ConStant.UPDATEAPPURI;
//        }
//    }
//
//    @Override
//    protected void initViews() {
//
//        new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item5)).setRightIcon(R.drawable.association_white, this);
//
//
//    }
//
//    @Override
//    protected void loadData() {
//        if (MyApp.getUserData() != null && MyApp.getUserData().getData() != null && MyApp.getUserData().getData().getUser() != null) {
//            tvInvidecode.setText(MyApp.getUserData().getData().getUser().getCode());
//            initAddressQRCode();
//        }
//    }
//
//    @Override
//    public void onClick(View v) {
//        switch (v.getId()) {
//            case R.id.rightItem:
////                if (MyApp.getMyTeamDataBean() == null) {
////                    ShowProgress();
////                    preenter.getMyTeamData();
//////                    showToast("加载中,请稍后尝试...");
////                    break;
////                }
//                startActivity(GroupActivity.class);
//                break;
//        }
//
//    }
//
//    private void initAddressQRCode() {
//
////        layoutView(lyQrcodeBody,CommonUtil.px2dip(this,470),CommonUtil.px2dip(this,600));
//
//        qrCodeBitmap = CodeUtils.createImage(xiazaiuri,
//                CommonUtil.dip2px(this, 144),
//                CommonUtil.dip2px(this, 144),
//                BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
//        imgAdressqrcode.setImageBitmap(qrCodeBitmap);
//
//        bodyBitmap=CommonUtil.getBitMapFromView(lyQrcodeBody);
//    }
//
//
//    private void layoutView(View v, int width, int height) {
//        // validate view.width and view.height
//        v.layout(0, 0, width, height);
//        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
//        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
//        // validate view.measurewidth and view.measureheight
//        v.measure(measuredWidth, measuredHeight);
//        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
//    }
//
//
//    private void copyWalletAddress(String msg) {
//        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
//        // 将文本内容放到系统剪贴板里。
//        if (cm != null) {
//            // 创建普通字符型ClipData
//
//            ClipData mClipData = ClipData.newPlainText("Label", msg);
//            // 将ClipData内容放到系统剪贴板里。
//            cm.setPrimaryClip(mClipData);
//        }
//        showToast(getString(R.string.profile_hint_item14));
//        tvCopy.setText(getString(R.string.profile_hint_item14));
//    }
//
//    /**
//     * 保存图片到指定路径
//     *
//     * @param context
//     * @param bitmap   要保存的图片
//     * @param fileName 自定义图片名称
//     * @return
//     */
//    public static boolean saveImageToGallery(Context context, Bitmap bitmap, String fileName) {
//        //系统相册目录
//        String storePath = Environment.getExternalStorageDirectory()
//                + File.separator + Environment.DIRECTORY_DCIM
//                + File.separator + "Camera" + File.separator;
//
//        // 保存图片至指定路径
////        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "qrcode";
//
//
//        File appDir = new File(storePath);
//        if (!appDir.exists()) {
//            appDir.mkdir();
//        }
//        File file = new File(appDir, fileName);
//        try {
//            FileOutputStream fos = new FileOutputStream(file);
//            //通过io流的方式来压缩保存图片(80代表压缩20%)
//            boolean isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
//            fos.flush();
//            fos.close();
//
//            //发送广播通知系统图库刷新数据
//            Uri uri = Uri.fromFile(file);
//            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
//            if (isSuccess) {
//                return true;
//            } else {
//                return false;
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return false;
//    }
//
//    @OnClick({R.id.tv_savebitmap, R.id.tv_copy, R.id.tv_invidecode})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.tv_savebitmap:
//                if (bodyBitmap == null) {
//                    showToast(getString(R.string.network_loading_hint1));
//                    break;
//                }
//                //存储权限
//                RxPermissions rxPermissions = new RxPermissions(this);
//                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                        .subscribe(new Observer<Boolean>() {
//                            @Override
//                            public void onSubscribe(Disposable d) {
//                            }
//
//                            @Override
//                            public void onNext(Boolean granted) {
//                                if (granted) {
//                                    if (saveImageToGallery(InviteFriendActivity.this, bodyBitmap, "" + getString(R.string.profile_hint_item17))) {
//                                        showToast(getString(R.string.profile_hint_item15));
//                                        tvSavebitmap.setText(getString(R.string.profile_hint_item16));
//                                    }
//                                }
//                            }
//
//                            @Override
//                            public void onError(Throwable e) {
//                            }
//
//                            @Override
//                            public void onComplete() {
//                            }
//                        });
//
//                break;
//            case R.id.tv_copy:
//                if (xiazaiuri.isEmpty()) {
//                    showToast(getString(R.string.network_loading_hint1));
//                    break;
//                }
//                copyWalletAddress(xiazaiuri);
//                break;
//            case R.id.tv_invidecode:
//                if (tvInvidecode.getText().toString().isEmpty()) {
//                    showToast(getString(R.string.network_loading_hint1));
//                    break;
//                }
//                copyWalletAddress(tvInvidecode.getText().toString());
//                break;
//        }
//    }
//
//    @Override
//    public void getData(Object o) {
//
//    }
//
//    @Override
//    public void jumpToLoginAct(int staue) {
//        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
//        }
//    }
//
//    @Override
//    public void onError(String error) {
//
//        showToast(getString(R.string.common_loaderrritry));
//    }
//
//    @Override
//    public void ShowProgress() {
//
//        showWaitDialog();
//    }
//
//    @Override
//    public void hideProgress() {
//
//        hideWaitDialog();
//    }
//
//    @Override
//    public void getMyTeamData(MyTeamData myTeamData) {
//        if (myTeamData.getStatus() == 0 && myTeamData.getData() != null) {
//            MyApp.setMyTeamDataBean(myTeamData.getData());
//            startActivity(GroupActivity.class);
//        }
//    }
//}